
package com.e885.util.numeric;

import com.e885.constant.util.CarryConstant;
import com.e885.exception.E885UtilException;

/**
 * 
 * @author Grady.Kao
 * @version 1.0
 * @company E885 Group
 * @copyright Copyright (c) 2000-2008
 */
public class IntegerUtil
{
	/**
	 * Parse String to be primitive int.<br>
	 * If the instance of the String(source) is null or its length is zero, we will return zero.
	 * 
	 * @param source to be parsed
	 * @param carry carry rule, {@link com.e885.constant.util.CarryConstant}
	 * @return a primitive int
	 * @throws E885UtilException can't pase source to be primitive int
	 */
	public static int parseString2Primitive( String source, int carry ) throws E885UtilException
	{
		return intValue( parseString2Integer( source, carry ) );
	}

	/**
	 * Parse String to be Integer.<br>
	 * If the instance of the String(source) is null or its length is zero, we will return null.
	 * 
	 * @param source to be parsed
	 * @param carry carry rule, reference:{@link com.e885.constant.util.CarryConstant}
	 * @return an Integer
	 * @throws E885UtilException can't pase string to be Integer
	 */
	public static Integer parseString2Integer( String source, int carry ) throws E885UtilException
	{
		if( source == null || source.length() == 0 )
			return null;

		if( !( carry == CarryConstant.ROUND_OFF || carry == CarryConstant.UNCONDITIONAL_CARRY || carry == CarryConstant.UNCONDITIONAL_DISCARD ) )
			throw new IllegalArgumentException( "carry is error" );

		try
		{
			if( source.indexOf( "." ) != -1 )
			{
				int intTemp = 0;

				double d = Double.parseDouble( source );

				if( carry == CarryConstant.UNCONDITIONAL_DISCARD )
					intTemp = ( int )d;
				else if( carry == CarryConstant.UNCONDITIONAL_CARRY )
					intTemp = ( int )d + 1;
				else
					intTemp = ( int )( d + 0.5 );

				return new Integer( intTemp );
			}

			return new Integer( source );
		}
		catch( NumberFormatException e )
		{
			throw new E885UtilException( "Can't parse string to be Integer:" + source );
		}
	}

	/**
	 * When the value of the argument is null, we will return zero.<br>
	 * Otherwise, we will return Integer.intValue()<br>
	 * reference:{@link java.lang.Integer#intValue()}
	 * 
	 * @param obj
	 * @return
	 */
	public static int intValue( Integer obj )
	{
		if( obj == null )
			return 0;

		return obj.intValue();
	}
}
